<template>
	<div>
		<div>
			<el-button class="addGDbtu" plain @click="dialogFormVisible = true">创建工单</el-button>
		</div>
		<el-dialog v-model="dialogFormVisible" title="创建任务" width="1000px" class="cjrw">
			<div>
				<el-form>
					<el-input class="gdnr" v-model="orderwork.ordernr" maxlength="1000" placeholder="输入工单内容"
						show-word-limit type="textarea" />
					<el-dialog v-model="dialogVisible">
						<img w-full :src="dialogImageUrl" alt="Preview Image" />
					</el-dialog>
				</el-form>
			</div>
			<div style="margin-top: 20px; margin-left: 40px; display: flex; gap: 20px;">
				<el-form-item label="工单类型(选填)">
					<el-select @change="handleSelectChange" v-model="orderwork.orderlx_id" clearable
						placeholder="请选择工单类型" style="width: 240px">
						<el-option v-for="item in gdlxoptions" :key="item.orderlx_id" :label="item.order_name"
							:value="item.orderlx_id" />
					</el-select>
				</el-form-item>
				<el-form-item v-if="orderwork.orderlx_id === 1">
					<el-select v-model="jixm.xmid" clearable placeholder="选择计费项目" style="width: 240px;">
						<el-option v-for="item in jfxmoptions" :key="item.billingltems_id"
							:label="item.billingltems_name" :value="item.billingltems_id" />
					</el-select>
				</el-form-item>
				<el-form-item v-if="orderwork.orderlx_id === 1">
					<el-input v-model="jfje" placeholder="输入金额"></el-input>
				</el-form-item>
			</div>
			<div style="margin-left: 40px;">
				<el-form-item label="所属房屋(选填)" class="gdly"><!-- :options="options2" -->
					<el-cascader v-model="lastNumber.xz" :options="options" :props="props1" placeholder="请选择" clearable
						:show-all-levels="false" style="width: 240px" />
				</el-form-item>
			</div>
			<div style="margin-top: 20px;margin-left: 50px;">
				<el-form-item label="工单起止时间" style="width: 500px;">
					<el-config-provider :locale="locale">
						<el-date-picker v-model="shtgvalue" :disabled-date="disabledDateFn" format="YYYY-MM-DD"
							value-format="YYYY-MM-DD" type="daterange" range-separator="至" start-placeholder="开始时间"
							end-placeholder="结束时间" />
					</el-config-provider>
				</el-form-item>
			</div>
			<div style="display: flex; align-items: center;margin-left: 75px;">
				<span style="color: red; margin-right: 5px;margin-top: -15px;">*</span>
				<el-form-item label="执行人" style="width: 700px;">
					<el-select v-model="gongdanexecutor" multiple placeholder="选择执行人(可多选)" style="width: 240px">
						<el-option v-for="item in zxroptions.user_name" :key="item.user_name" :label="item.user_name"
							:value="item.user_name" />
					</el-select>
				</el-form-item>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button class="qx" @click="dialogFormVisible=false">取消</el-button>
					<el-button class="qd" @click="yes">确定</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
	import { useRouter } from 'vue-router';
	import { ElMessage } from 'element-plus'
	import zhCn from "element-plus/dist/locale/zh-cn";
	import { ref, reactive, computed, onMounted, watch } from "vue"
	import $http from "../router/AxiosApi";
	var getTime = new Date().getTime(); //获取到当前时间戳
	var time = new Date(getTime); //创建一个日期对象
	function nowDate(time) {
		var year = time.getFullYear(); // 年
		var month = (time.getMonth() + 1).toString().padStart(2, '0'); // 月
		var date = time.getDate().toString().padStart(2, '0'); // 日
		var hour = time.getHours().toString().padStart(2, '0'); // 时
		var minute = time.getMinutes().toString().padStart(2, '0'); // 分
		var second = time.getSeconds().toString().padStart(2, '0'); // 秒
		return (
			year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second
		)
	}
	// 转换为字符串类型
	var formattedTime = nowDate(time);
	console.log("当前时间:", formattedTime); // 输出格式化后的时间字符串

	// 如果需要将其转换为普通字符串类型，直接使用 formattedTime 即可
	var stringTime = formattedTime.toString();
	console.log("转换后的字符串类型:", stringTime);
	const orderwork = reactive({
		orderlx_id: '',
		order_hao: '',
		ordernr: '',
		order_name: '',
		adress: '',
		qz_time: '',
		executor: ''
	})
	let gdlxoptions = reactive([])
	const billingltemsId = ref(null)
	$http.post("OrderLX").then((res) => {
		gdlxoptions = res.data.data
		billingltemsId.value = res.data.data[0].billingltems_id
		console.log(res.data.data)
		//console.log("计费项目id:", billingltemsId.value)
	})
	const selectedOrderlxId = ref(null); // 用于存储选择的工单类型id
	function handleSelectChange(value) {
		selectedOrderlxId.value = value; // 更新选中的工单类型id
		const selectedOption = gdlxoptions.find(item => item.orderlx_id === value);
		if (selectedOption) {
			orderwork.order_name = selectedOption.order_name; // 更新工单名称
			console.log('工单类型id:', value);
			if (orderwork.order_name === '有偿服务') {
				console.log("计费项目id:", billingltemsId.value);
			}
		}
	}
	const locale = zhCn;
	const disabledDateFn = (time) => {
		if (time.getTime() < Date.now() - 8.64e7) {
			return true;
		} else {
			return false;
		}
	};
	const zxrvalue = ref([])
	const zxroptions = reactive(
		{ user_name: [] }
	)
	$http.post("ZhiXingRen").then((res) => {
		zxroptions.user_name = res.data.data
	})
	const dialogFormVisible = ref(false)
	// const form = reactive({
	// 	name: '',
	// 	region: '',
	// 	date1: '',
	// 	date2: '',
	// 	delivery: false,
	// 	type: [],
	// 	resource: '',
	// 	desc: '',
	// })

	const dialogImageUrl = ref('')
	const dialogVisible = ref(false)

	//拼接时间
	const shtgvalue = ref([])
	const formattedRange = computed(() => {
		if (shtgvalue.value.length === 2) {
			const startDate = shtgvalue.value[0];
			const endDate = shtgvalue.value[1];
			return `${startDate} 至 ${endDate}`;
		} else {
			return '';
		}
	});
	const Billingltems = reactive(
		{
			billingltems_id: '',
			billingltems_name: '',
			freightbasis: ''
		}
	)
	const Freightbasis = ref(null)
	$http.post("findBillingltems", Billingltems).then((res) => {
		Freightbasis.value = res.data.data[0].freightbasis
		console.log("单价", Freightbasis.value)
		console.log("计费标准:", res.data)
	})
	const emit = defineEmits();
	const gongdanexecutor = ref([])

	const lastNumber = reactive({
		xz: []
	})
	const options = reactive([]);
	const props1 = {
		checkStrictly: true,
	};

	const data = reactive({
		expense: [],
		house: [],
		item: [],
	});

	const form = reactive({
		houseId: '',
		unitId: '',
		buildingId: '',
		regionId: '',
		billingItemsName: '',
		regionName: '',
		buildingName: '',
		unitName: '',
		houseNumber: ''
	});

	onMounted(() => {
		loadAll();

	});
	const loadAll = async () => {
		try {
			const res = await $http.post("orderfindAll");
			data.house = res.data.data;
			console.log("房屋:", data.house);

			if (data.house && data.house.length > 0) {
				const regions = data.house.map(house => ({
					value: house.regionName,
					label: house.regionName,
					children: [
						{
							value: house.buildingName,
							label: house.buildingName,
							children: [
								{
									value: house.unitName,
									label: house.unitName,
									children: [
										{
											value: house.houseNumber,
											label: house.houseNumber,
										},
									],
								},
							],
						},
					],
				}));

				// 更新 options 数组
				options.splice(0, options.length, ...regions);
			}
		} catch (error) {
			console.error("加载数据失败:", error);
		}
	};
	const House_Id = ref(null)
	watch(() => lastNumber.xz, (newValue) => {
		console.log("选择的值:", newValue);

		if (newValue.length > 0) {
			const lastItem = newValue[newValue.length - 1];
			// 将lastItem转换为String  
			const lastItemAsString = String(lastItem);
			console.log("最后一个选项:", lastItemAsString);
			// 打印整个选项数据结构，检查 `value` 是否是 `houseNumber`  
			console.log("完整的选项数据:", options);
			$http.post("findAll1", { houseNumber: lastItemAsString }).then((res) => {
				console.log("查出来", res.data);
				House_Id.value = res.data.data[0].houseId
			});
		} else {
			console.log("没有选择任何项");
		}
	});
	const yes = () => {
		if (!orderwork.ordernr) {
			ElMessage.error('工单内容不能为空！');
			return;
		}
		if(!orderwork.orderlx_id){
			ElMessage.error('工单类型不能为空！');
			return;
		}
		if (!gongdanexecutor.value.length) {
			ElMessage.error('执行人不能为空！');
			return;
		}
		if (lastNumber.xz === undefined) {
			console.log("未选择");
			form.buildingId = ''
			form.houseId = ''
			form.regionId = ''
			form.unitId = ''
		} else {
			form.regionId = lastNumber.xz[0]; // 第一个选项作为 regionId
			if (lastNumber.xz.length >= 2) {
				form.buildingId = lastNumber.xz[1]; // 第二个选项作为 buildingId
			}
			if (lastNumber.xz.length >= 3) {
				form.unitId = lastNumber.xz[2]; // 第三个选项作为 unitId
			}
			if (lastNumber.xz.length >= 4) {
				form.houseId = lastNumber.xz[3]; // 第四个选项作为 houseId
			}
			const fw = lastNumber.xz.map(name => name).join('-')
			console.log("房屋地址:", fw)
			$http.post("Orderwork", orderwork).then((res) => {
				const data = res.data.data;
				// 提取所有 order_hao 的值
				const orderHaos = data.map(item => item.order_hao);
				// 查找最大的 order_hao
				const maxOrderHao = orderHaos.reduce((max, current) => {
					return (max.localeCompare(current) > 0) ? max : current;
				});
				// 提取日期和编号部分
				const [datePart, numPart] = maxOrderHao.split('-');
				// 将编号部分转换为整数并自增
				const newNum = (parseInt(numPart, 10) + 1).toString().padStart(numPart.length, '0');
				// 生成新的 order_hao
				const newOrderHao = `${datePart}-${newNum}`;
				console.log('最大 order_hao:', maxOrderHao);
				console.log('新的 order_hao:', newOrderHao);

				const xzzxr = gongdanexecutor.value.map(name => name).join(', ')
				$http.post("addOrderWork", {
					order_hao: newOrderHao,
					chuang_time: stringTime,
					qz_time: formattedRange.value,
					state: '待审核',
					executor: xzzxr,
					zjgx_time: stringTime,
					ordernr: orderwork.ordernr,
					orderlx_id: selectedOrderlxId.value,
					adress: fw
				}).then((res) => {
					// 检查是否选择了“住户报修”
					console.log("起止时间", formattedRange.value)
					if (orderwork.order_name === '住户报修' && billingltemsId.value !== null) {
						$http.post("findCost").then((res) => {
							console.log("费用:", res.data.data)
							const data = res.data.data || [];

							// 如果数据不为空，找出最大的 cost_id，否则初始值为 0
							const maxCostId = data.length > 0
								? data.reduce((max, item) => item.cost_id > max ? item.cost_id : max, -Infinity)
								: 0;
							// 自增
							const newCostId = maxCostId + 1;
							console.log("最大的 cost_id:", maxCostId);
							console.log("自增后的 cost_id:", newCostId);
							$http.post("AddBillingltems", {
								cost_id: newCostId,
								billingltems_id: jixm.xmid,
								cost_state: '未付款',
								fyqz_time: formattedRange.value,
								fyje: jfje.value,
								yfkje: jfje.value,
								danjia: jfje.value,
								fyssy: formattedTime,
								sc_time: formattedTime
							}).then((res) => {
								// 处理计费项目添加成功的逻辑
								console.log('计费项目添加成功');
							}).catch((error) => {
								// 处理计费项目添加失败的逻辑
								console.error('计费项目添加失败:', error);
							});
							$http.post("addFwfyconnect", {
								cost_id: newCostId,
								house_id: House_Id.value
							}).then((res) => {
								console.log("添加成功")
							})
						})
					}
					ElMessage({
						message: '创建工单成功',
						type: 'success',
						plain: true,
					})
					orderwork.ordernr = ''
					orderwork.executor = ''
					orderwork.orderlx_id = ''
					shtgvalue.value = []
					gongdanexecutor.value = []
					lastNumber.xz = []
					dialogFormVisible.value = false
					emit('update'); // 触发自定义事件
				})
			});
		}
		console.log(jixm.xmmc)
	}
	let jfxmoptions = reactive([])
	const jixm = reactive({
		xmmc: '',
		xmid:''
	})
	const jfje = ref('')
	$http.post("/BillingltemsList").then((res) => {
		console.log("计费项目", res.data)
		jfxmoptions = res.data.data
	})
</script>

<style scoped>
	.addGDbtu {
		background-color: #00C36D;
		color: white;
	}

	.cjrw {
		border-radius: 10px;
	}

	.gdnr {
		width: 900px;
	}

	.qd {
		width: 100px;
		height: 40px;
		background-color: #00C36D;
		color: white;
	}

	.qx {
		width: 100px;
		height: 40px;
		background-color: #F5F5F5;
		border: none;
	}
</style>